<template>
  <div>
    <FormDialog
      :title="title"
      :isShow.sync="isShow"
      :width="width"
      :height="height"
      v-on:resetForm="close()"
    >
      <div class="addArea">
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
          <el-form-item label="地区名称：" prop="name">
            <el-input v-model="form.name" placeholder="例如：北湖区"/>
          </el-form-item>
          <el-form-item label="上级节点：">
            <TreeSelect
              size="small"
              :data="treeData"
              :defaultProps="defaultProps"
              :checkedKeys="checkedKeys"
              v-model="selectClassify"
              nodeKey="value"
            />
          </el-form-item>
          <el-form-item>
            <el-button size='mini' type="primary" @click="onSubmit()">提交</el-button>
            <el-button size='mini' @click="close">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </FormDialog>
  </div>
</template>

<script>
import FormDialog from "@/components/index/formDialog";
import TreeSelect from "@/components/index/TreeSelect";
import { getProvince,addArea } from "@/js/api/manage";
export default {
  name: "addArea",
  components: {
    FormDialog,
    TreeSelect,
  },
  data() {
    return {
      title: "新增地区",
      isShow: false,
      width: "600px",
      height: "1000px",
      treeData: [],
      checkedKeys: [],
      selectClassify: {},
      defaultProps: {
        children: "children",
        label: "name",
      },
      form:{
        name:"",
        pid:0,
      },
      rules: {
        name: [
          { required: true, message: "请填写地区名称", trigger: "blur" },
        ],
      }
    };
  },
  created() {
    this.loadList();
  },
  methods: {
    show(data) {
      if(data){
        this.checkedKeys = [{value:data.name}]
        this.selectClassify.id = data.id
      }
      this.isShow = true;
      this.loadList()
    },
    loadList() {
      getProvince().then((response) => {
        if (response.data.state) {
          this.treeData = [response.data.data.data];
        }
      });
    },
    onSubmit(){
      if(JSON.stringify(this.selectClassify.id)!=undefined){
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.pid = this.selectClassify.id
            addArea(this.form).then(response=>{
              if(response.data.state){
                this.utils.tips.success("添加成功")
                this.close()
                this.$emit("refresh")
              }else{
                this.utils.tips.error(response.data.msg)
              }
            })
          }
        });
      }else{
        this.utils.tips.error("请选择上级地区")
      }
    },
    close() {
      this.isShow = false;
      this.$refs['form'].resetFields();
    },
  },
};
</script>

<style lang="less">
</style>